import com.sun.rowset.CachedRowSetImpl;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author tub
 */
public class ExploreTableModel extends AbstractTableModel implements TableModel
{
    public ExploreTableModel(CachedRowSetImpl crs) throws SQLException
    {
        this.crs = crs;
        size = crs.size();
        meta = crs.getMetaData();
    }

    public int getRowCount()
    {
        return size;
    }

    public int getColumnCount()
    {
        int count = 0;

        try
        {
            count = meta.getColumnCount();
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }

        return count;
    }

    public void addRow() throws SQLException, IOException
    {
        Connection conn = MusicFrame.getConnection();

        size++;
        crs.setTableName("Label");
        crs.moveToInsertRow();
        for (int i = 1; i <= getColumnCount(); i++)
            crs.updateString(i, "");

        crs.insertRow();
        crs.moveToCurrentRow();
        conn.close();

        fireTableDataChanged();
    }

    @Override
    public String getColumnName(int columnIndex)
    {
        String name = "";

        try
        {
            name = meta.getColumnName(columnIndex + 1);
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }

        return name;
    }

    public Object getValueAt(int rowIndex, int columnIndex)
    {
        Object value = null;

        try
        {
            crs.absolute(rowIndex + 1);
            value = crs.getObject(columnIndex + 1);
        }
        catch (SQLException ex)
        {
            ex.printStackTrace();
        }

        return value;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex)
    {
        return true;
    }

    @Override
    public void setValueAt(Object val, int rowIndex, int columnIndex)
    {
        try 
        {
            Connection conn = MusicFrame.getConnection();
            crs.setTableName("Label");
            crs.absolute(rowIndex + 1);
            crs.updateObject(columnIndex + 1, val.toString());
            crs.updateRow();
            crs.acceptChanges(conn);
            conn.close();
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }


    public CachedRowSetImpl getCrs()
    {
        return crs;
    }


    private ResultSetMetaData meta;
    private CachedRowSetImpl crs;
    private int size;
}
